package com.heima.media.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.media.dto.ChannelDto;
import com.heima.media.entity.WmChannel;
import com.heima.media.mapper.WmChannelMapper;
import com.heima.media.service.IWmChannelService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import java.util.Collection;
import java.util.Date;
import java.util.Map;
import java.util.function.Function;
import java.util.Date;

@Service
public class WmChannelServiceImpl extends ServiceImpl<WmChannelMapper,WmChannel> implements IWmChannelService {

    @Override
    public ResponseResult listByName(ChannelDto dto) {

        //判断dto不能为空  如果为空直接返回一个错误提示
        if(dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

//        select * from wm_channel where name like '%??%' limit start , size
//        dto.getName()
        LambdaQueryWrapper<WmChannel> queryWrapper = new LambdaQueryWrapper<>();

        if(StringUtils.isNotBlank(dto.getName())){
            queryWrapper.like(WmChannel::getName,dto.getName());
        }
//        分页查询 一定要添加mybatisPlus的分页插件
        Page<WmChannel> page = new Page<>(dto.getPage(),dto.getSize());

        Page<WmChannel> page1 = this.page(page, queryWrapper);
        return new PageResponseResult(dto.getPage(),dto.getSize(),page1.getTotal(),page1.getRecords());//  当前页码, 每页显示条数,  总条数, 当前页数据
    }

    @Override
    public ResponseResult saveWmChannel(WmChannel wmChannel) {
        if(wmChannel==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

//        判断这个频道是否已经存在
//        先查询
        LambdaQueryWrapper<WmChannel> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmChannel::getName,wmChannel.getName());

        WmChannel one = this.getOne(queryWrapper);
        if(one!=null){ //意味着查到了一个同名的频道
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST);
        }
        wmChannel.setCreatedTime(new Date());
        this.save(wmChannel);
        return ResponseResult.okResult();
    }
}
